/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.core.tapestry.services.assets;

import java.io.File;
import java.util.Collection;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.activation.MimetypesFileTypeMap;

import org.apache.commons.io.FilenameUtils;
import org.apache.tapestry5.services.Request;

import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil;

/**
 * @author Martin Papy
 *
 */
public class OfsFilesUtils {
	public static final String FILE_SEPARATOR = System.getProperty("file.separator");
	
	public static AtomicBoolean isRegisterNeeded = new AtomicBoolean(true);
	
	static {
		if(isRegisterNeeded.getAndSet(false)){
			MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
			MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.ExtensionMimeDetector");
		}
	}
	

	public static String cleanFileName(String fileName, boolean makeUnique) {
		if(makeUnique) {
			String ext = FilenameUtils.getExtension(fileName);
			return UUID.randomUUID().toString().toLowerCase() + "." + ext;
		}
		return fileName.replaceAll("([a-z][A-Z]-_\\.)+", "_");
	}
	
	public static String sanitiseDirPath(String dirPath) {
		String path = dirPath.trim();
		
		if(path.startsWith("file://")){
			path = path.substring("file://".length());
		}
		
		if (!path.endsWith(FILE_SEPARATOR)) {
			path += FILE_SEPARATOR;
		}

		File dir = new File(path);

		if (!dir.exists()) {
			dir.mkdirs();
		}

		return dir.getAbsolutePath();
	}
	
	@SuppressWarnings("unchecked")
	public static String getMimeType(File file) {
		Collection<MimeType> mimes = MimeUtil.getMimeTypes(file);

		if (!mimes.isEmpty()) {
			return MimeUtil.getMostSpecificMimeType(mimes).toString();
		}
		
		//Fallback method
		return new MimetypesFileTypeMap().getContentType(file); 
	}
	
	public static String computeSubDirectory(String fileName) {
		return fileName.substring(0, 1) + OfsFilesUtils.FILE_SEPARATOR + fileName.substring(1, 2) + OfsFilesUtils.FILE_SEPARATOR;
	}
	
	public static String computerBaseFilerPath(String homeDir, String subDir){
		File baseDir;
		if(homeDir.startsWith("classpath")){
			baseDir = new File(sanitiseDirPath(OfsAssetFactory.TEMP_FOLDER));
		} else {
			baseDir = new File(sanitiseDirPath(homeDir));
		}
		
		baseDir = new File(baseDir,OfsAssetFactory.OFS_RESOURCE_FOLDER);
		
		baseDir = new File(baseDir, subDir);
		
		return sanitiseDirPath(baseDir.getAbsolutePath());
    }
	
	public static String computeFullStoreFilePath(String basePath, String fileName){
		File path = new File(basePath, computePartialStoreFilePath(fileName));
		return path.getAbsolutePath();
	}
	
	public static String computePartialStoreFilePath(String fileName){
		StringBuffer path = new StringBuffer(OfsFilesUtils.computeSubDirectory(fileName));
			path.append(fileName);
		return path.toString();
	}	
	
	public static String getVirtualPathFromUrl(String url, Request request, String assetPath){
		String ofsPrefix =  assetPath + OfsAssetFactory.OFS_VIRTUAL_FOLDER + "/";
		String fullOfsPrefix = request.getContextPath() + ofsPrefix;
		if(url.startsWith(ofsPrefix)){
			return url.substring(ofsPrefix.length());
		}
		
		if(url.startsWith(fullOfsPrefix)){
			return url.substring(fullOfsPrefix.length());
		}
		return null;
	}
	
	public static String getPrefixedPathFromUrl(String url, Request request, String assetPath){
		return getOfsPrefix() + getVirtualPathFromUrl(url, request, assetPath);
	}

	/**
	 * @param path
	 * @return stripped path
	 */
	public static String stripPrefix(String path) {
		if(path.startsWith(getOfsPrefix())){
			return path.substring(getOfsPrefix().length());
		}
		return path;
	}
	
	private static String getOfsPrefix(){
		return OfsBindingFactory.OFS_BINDING_PREFIX + ":";
	}
}
